<template>
  <div id="labreportitemRefer">
    <Splitpanes horizontal class="horizontalLine">
      <Pane size="50">
        <vxe-toolbar perfect>
          <template #buttons>
            <div class="smallToolTitle">参考范围</div>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="iloading" @click="findItemDictRefer"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增" @click="handleAdd"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" @click="handleSave" :loading="saveLoading"></vxe-button>
            <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="handleDelete"></vxe-button>
          </template>
          <template #tools>
            <div class="flex justify-end margin-right-xs">
              <vxe-button type="text" class="button-blue" content="特殊参考值规则" @click="openDialog"></vxe-button>
            </div>
          </template>
        </vxe-toolbar>
        <div class="tableBody">
          <vxe-table ref="itemDictReferTable" :loading="loading" class="mytable-scrollbar" :row-config="{ isCurrent: true, isHover: true }" :data="tableList" border style="width: 100%" height="auto" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }" @current-change="rowClick" resizable show-overflow keep-source :column-config="{ resizable: true }">
            <vxe-column field="seq" title="序号" width="30" type="seq" align="center"></vxe-column>

            <vxe-column field="lowerLimit" title="下限" width="50" align="center" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                <div>{{ row.lowerLimit }}</div>
              </template>
              <template #edit="{ row, rowIndex }">
                <vxe-input v-model="row.lowerLimit" placeholder="请输入下限" style="width: 100%" @blur="handleBlurLowerLimit(row, rowIndex)"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="upperLimit" title="上限" width="50" align="center" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                <div>{{ row.upperLimit }}</div>
              </template>
              <template #edit="{ row, rowIndex }">
                <vxe-input v-model="row.upperLimit" placeholder="请输入上限" style="width: 100%" @blur="handleBlurUpperLimit(row, rowIndex)"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="range" title="参考范围" :show-overflow="false" width="100" align="left" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                <div>{{ row.range }}</div>
              </template>
              <template #edit="{ row }">
                <!-- <vxe-input v-if="row.range&&row.range.length<=20" v-model="row.range" placeholder="参考范围" style="width: 100%"></vxe-input> -->
                <vxe-textarea v-model="row.range" placeholder="参考范围" style="width: 100%"></vxe-textarea>
              </template>
            </vxe-column>
            <vxe-column field="factorDescribe" title="条件描述" align="center" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                <div>{{ row.factorDescribe }}</div>
              </template>
              <template #edit="{ row }">
                <vxe-input v-model="row.factorDescribe" style="width: 100%"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="isEnable" width="90" title="是否启用" align="center">
              <template #default="{ row }">
                <vxe-switch v-model="row.isEnable" size="mini" open-label="是" close-label="否" open-value="1" close-value="0"></vxe-switch>
              </template>
            </vxe-column>
            <vxe-column field="factor" title="条件" align="center" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                <div>{{ row.factor }}</div>
              </template>
              <template #edit="{ row }">
                <vxe-input v-model="row.factor" style="width: 100%"></vxe-input>
              </template>
            </vxe-column>

            <vxe-column field="referList" title="规则中设置数据" align="center" :visible="false"></vxe-column>
            <vxe-column field="selectValue" title="选中的规则" align="center" :visible="false"></vxe-column>
          </vxe-table>
        </div>

      </Pane>
      <Pane size="50">
        <div class="toolbartitle">规则设置</div>
        <div class="tableBody">
          <formulaTools ref="referFormRef" @repressChange="getRefer" />
        </div>
      </Pane>
    </Splitpanes>

    <vxe-modal v-model="showModal" width="85vw" height="75vh">
      <template #title>
        <span>参考范围特殊规则设置</span>
      </template>
      <template #default>
        <Splitpanes>
          <Pane size="40">
            <vxe-toolbar perfect>
              <template #buttons>
                <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="iloading" @click="findSpecialRules"></vxe-button>
                <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增" @click="addSpecialRule"></vxe-button>
                <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteSpecialRule"></vxe-button>
              </template>
            </vxe-toolbar>
            <div style="height:calc(100% - 40px)">
              <vxe-table ref="specialRuleTabRef" show-overflow auto-resize height="auto" :row-config="{isCurrent:true}" :data="specRulesTableList" @current-change="specialRuleRowClick">
                <vxe-column field="seq" title="顺序号" width="50"></vxe-column>
                <vxe-column field="exceptionSymbol" title="结果标识" width="60">
                  <template #default="{row}">
                    <span>{{calcResultFlagText(row)}}</span>
                  </template>
                </vxe-column>
                <vxe-column field="resultFlag" title="结果标识文字" width="80"></vxe-column>
                <vxe-column field="resultType" title="结果数据类型" width="80">
                  <template #default="{row}">
                    <span v-if="row.resultType===1||row.resultType==='1'">整形</span>
                    <span v-if="row.resultType===2||row.resultType==='2'">浮点型</span>
                    <span v-if="row.resultType===3||row.resultType==='3'">字符串</span>
                  </template>
                </vxe-column>
                <vxe-column field="factor" title="公式"></vxe-column>
              </vxe-table>
            </div>
          </Pane>
          <Pane size="40">
            <vxe-toolbar perfect>
              <template #buttons>
                <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" @click="saveSpecialRule" :loading="saveLoading"></vxe-button>
              </template>
            </vxe-toolbar>
            <el-form ref="ruleFormRef" :model="ruleForm" :label-position="'right'" status-icon label-width="120px" class="demo-ruleForm">
              <el-form-item label="顺序" prop="seq">
                <el-input v-model="ruleForm.seq" autocomplete="off" />
              </el-form-item>
              <el-form-item label="结果标志" prop="exceptionSymbol">
                <!-- <el-input v-model="ruleForm.exceptionSymbol" autocomplete="off" /> -->
                <VxeDictSelection style="width:100%;border-radius:5px;" :tableColumn="[
                { field: 'code', title: '编码', width: `60px` },
                { field: 'name', title: '名称', minWidth: `80px` }
              ]" :url="`/api/sys/basDictDetail/findDictDetailList`" :displayTextObj="ruleForm.exceptionSymbol" @confirmClick="dropSelectConfirm" :aimKeys="[{ targetField: 'exceptionSymbol', sourceField: 'code' }]" :dataObj="{ code: 'resultFlag' }"></VxeDictSelection>
              </el-form-item>
              <el-form-item label="结果标志文字" prop="resultFlag">
                <el-input v-model="ruleForm.resultFlag" autocomplete="off" />
              </el-form-item>
              <el-form-item label="结果数值类型" prop="resultType">
                <el-radio-group v-model="ruleForm.resultType" size="small" is-button>
                  <el-radio-button :label="1">整形</el-radio-button>
                  <el-radio-button :label="2">浮点型</el-radio-button>
                  <el-radio-button :label="3">字符串</el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="公式" prop="factor">
                <el-input v-model.number="ruleForm.factor" :rows="8" type="textarea" :input-style="{height:'45%'}" />
              </el-form-item>
              <el-form-item>
                <vxe-button type="text" class="button-blue" content="结果值公式" @click="resulthandle"></vxe-button>
                <vxe-button type="text" class="button-blue" content="OD值公式" @click="odhandle"></vxe-button>
                <vxe-button type="text" class="button-blue" content="CutOff值公式" @click="cutoffhandle"></vxe-button>
              </el-form-item>
              <el-form-item>
                <div class="text-bold text-orange test-shadow">
                  <p>1、公式中testresult是结果(注意大小写)</p>
                  <p>2、当与数字进行比较时,写法: testresult &gt; 1</p>
                  <p>3、当与字符进行比较时,写法:'testresult' = '阴性'</p>
                  <p>4、公式支持Sql方法,例如'testresult' Like '%阳%'; Left(testresult,1)='&lt;'等</p>
                </div>
              </el-form-item>
            </el-form>
          </Pane>
        </Splitpanes>
      </template>
    </vxe-modal>
  </div>
</template>

<script lang="ts" setup>
// 引入组件区 ==========
import { ref, reactive, onMounted, getCurrentInstance, watch, defineProps } from 'vue';
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '../../../utils/CommonMessage';
import { AppStore } from '../../../stores/store';
import { Splitpanes, Pane } from 'splitpanes';
import { IsEmpty } from '@/utils/common';
import VxeDictSelection from '@/components/VxeDictSelection.vue';
import formulaTools from '../../../components/FormulaTools.vue';

// 全局变量定义区 ==========
let iloading = ref(false); //按钮刷新状态
let props = defineProps({
  form: {}, //表单
  itemClassDict: Array as () => String[], //项目归类字段
  instrClassDict: Array as () => String[], //仪器大类字典
  reportGroupDict: Array as () => String[], //报告单元字典
  itemKindDict: Array as () => String[], //结果类型字典
  rptGroupId: String
}) as any;
let showModal = ref(false);/**特殊规则弹窗 */
let ruleForm = reactive({
  id: '',
  seq: 1,
  resultFlag: '',
  resultType: 1,/**1 整形 2浮点型 3字符串型 */
  factor: '',
  itemNo: '',
  rptGroup: '',
  isEnable: 1,
  exceptionSymbol: 'M'
});/**特殊规则表单对象 */
let ruleFormRef = ref(null);/**特殊规则表单Ref对象 */
let specRulesTableList = reactive([]);/**特殊规则列表 */
let specialRuleTabRef = ref(null);/**特殊规则列表对象 */
let dictResultFlagList = reactive([]);/**结果标志 基础字典 */

// 方法定义区 =============
defineExpose({ initPage });
let store = AppStore();
let showLoading = ref(false);
let { proxy }: any = getCurrentInstance();
let saveLoading = ref(false); //保存

// 方法定义区 =============
onMounted(() => {
  findItemDictRefer();
});
let tableList = reactive([]);
let loading = ref(false);
let rptGroup = '';
let itemNo = '';
let referFormRef: any = ref(null); //规则回显数据
let referForm = {
  selectValue: '',
  referList: ''
};
//上限光标移出事件
function handleBlurUpperLimit(row, rowIndex) {
  if (!IsEmpty(row.lowerLimit)) {
    tableList[rowIndex].range = row.lowerLimit + '-' + row.upperLimit;
  }
}
//下限光标移出事件
function handleBlurLowerLimit(row, rowIndex) {
  if (!IsEmpty(row.upperLimit)) {
    tableList[rowIndex].range = row.lowerLimit + '-' + row.upperLimit;
  }
}

//左侧列表点击之后传来的值
function initPage(row: any) {
  findDictResultFlag();
  if (row !== null) {
    rptGroup = row.rptGroup;
    itemNo = row.itemNo
    if (!IsEmpty(row.rptGroup)) {
      findItemDictRefer();
    }
  }
}
/**加载结果标志字典数据 */
function findDictResultFlag() {
  dictResultFlagList.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    .get(url, { params: { code: 'resultFlag' } })
    .then((res: any) => {
      dictResultFlagList.length = 0;
      if (res && res.status && res.status.code === 1) {
        Object.assign(dictResultFlagList, res.data);
      }
    })
    .catch((err: any) => {
      //todo
    });
}
function findItemDictRefer() {
  tableList.length = 0;
  if (IsEmpty(rptGroup)) {
    return;
  }

  iloading.value = true;
  loading.value = true;
  const url = '/lab/itemDictRefer/findItemDictRefer';
  proxy.$http
    .get(url, { params: { itemNo: itemNo, rptGroup: rptGroup } })
    .then((res: any) => {
      if (res.status.code === 200) {
        tableList.length = 0;
        tableList.push(...res.data);
        if (tableList.length > 0) {
          rowClick({
            row: tableList[0],
            rowIndex: 0
          });
        } else {
          referForm.referList = '';
          referForm.selectValue = '';
          referFormRef.value.initReferForm(referForm);
        }
      }
      iloading.value = false;
      loading.value = false;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
      iloading.value = false;
      loading.value = false;
    });
}

let rowdata = {}; //点击当前行的数据
let rowIndexClick = 0; //点击当前行下标
// 表格点击当前行
function rowClick({ row, rowIndex }: any) {
  rowIndexClick = rowIndex;
  rowdata = row;
  loading.value = false;
  const $itemDictReferTable = proxy.$refs.itemDictReferTable;
  if ($itemDictReferTable) {
    $itemDictReferTable.setCurrentRow(row);
  }
  referForm.referList = row.referList;
  referForm.selectValue = row.selectValue;
  referFormRef.value.initReferForm(referForm);
}

//删除参考范围信息
function handleDelete() {
  if (rowdata.id === '') {
    //没有做存储时，直接删除当前新增的列
    tableList.splice(rowdata.seq - 1, 1);
    return;
  }
  //凡是存储到库中的数据则需要清除库中的数据
  proxy.$http
    .post('/lab/itemDictRefer/deleteItemDictRefer', { id: rowdata.id })
    .then((res: any) => {
      if (res.status.code === 1) {
        findItemDictRefer();
        VxeMessage('删除成功', VxeNotifyType.success);
      } else {
        return;
      }
    })
    .catch((err: any) => {
      VxeMessage('删除异常', VxeNotifyType.error);
    });
}

// 新增参考范围
function handleAdd() {
  tableList.push({
    id: '',
    seq: tableList.length + 1,
    upperLimit: '',
    lowerLimit: '',
    factor: '',
    range: '',
    itemNo: itemNo,
    rptGroup: rptGroup,
    selectValue: '',
    referList: '',
    factorDescribe: '',
    isEnable: '1'
  });
}
let sqlExpress = '';
let referListJson = '';
let selectValue = '';
let factorDescribe = '';

//规则组件返回值
function getRefer(referTab: any) {
  // 实时插入点击的规则当前行中
  if (tableList.length > 0) {
    tableList[rowIndexClick].referList = IsEmpty(JSON.stringify(referTab.tab)) ? '' : JSON.stringify(referTab.tab);
    tableList[rowIndexClick].factor = IsEmpty(referTab.sqlExpress) ? '' : referTab.sqlExpress;
    tableList[rowIndexClick].selectValue = IsEmpty(JSON.stringify(referTab.selectValue)) ? '' : JSON.stringify(referTab.selectValue);
    tableList[rowIndexClick].factorDescribe = IsEmpty(referTab.factorDescribe) ? '' : referTab.factorDescribe;
  }
}

let itemDictReferTable = ref();
// 点击修改新增保存
async function handleSave() {
  if (tableList.length === 0) {
    VxeMessage('务必先新增参考范围-----点击【新增】设置区间范围》》规则设置', VxeNotifyType.error);
    return;
  }
  saveLoading.value = true;
  // 获取表格实例
  const $Xtable = itemDictReferTable.value;
  if ($Xtable) {
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords().filter((item) => item.id !== '');

    // 拿到列表中id为空的为新增
    const InsertRecords = tableList.filter((item) => item.id === '');

    // 遍历发起请求  将筛选出有id的每一个对象（修改过的） 作为参数传递给后端
    if (updateRecords && updateRecords.length > 0) {
      updateRecords.forEach((e: any) => {
        let itemDictReferAddParam = e;
        proxy.$http
          .post('/lab/itemDictRefer/editItemDictRefer', itemDictReferAddParam)
          .then((res: any) => {
          })
          .catch((err: any) => {
            VxeMessage('修改异常', VxeNotifyType.error);

          });
      });
      VxeMessage('修改成功', VxeNotifyType.success);
    }
    if (InsertRecords && InsertRecords.length > 0) {
      //新增参考范围
      InsertRecords.forEach((e: any) => {
        proxy.$http
          .post('/lab/itemDictRefer/addItemDictRefer', e)
          .then((res: any) => {
          })
          .catch((err: any) => {
            VxeMessage('创建异常', VxeNotifyType.error);
          });
      });
      VxeMessage('创建成功', VxeNotifyType.success);
    }
    setTimeout(() => {
      findItemDictRefer();
      saveLoading.value = false;
    }, 500);
  } else {
    return;
  }
}
/**打开弹窗 */
function openDialog() {
  showModal.value = true;
  findSpecialRules();
}
/**查询特殊规则 */
function findSpecialRules() {
  specRulesTableList.length = 0;
  const url = '/lab/itemDictSpecialRules/findItemDictSpecialRules';
  proxy.$http
    .get(url, { params: { itemNo: itemNo, rptGroup: rptGroup } })
    .then((res: any) => {
      if (res.status.code === 1) {
        specRulesTableList.push(...res.data);
        if (specRulesTableList.length > 0) {
          specialRuleRowClick({ row: specRulesTableList[0] });
        }
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
/**新增规则 */
function addSpecialRule() {
  ruleForm.id = '';
  ruleForm.seq = specRulesTableList.length + 1;
  ruleForm.resultFlag = '';
  ruleForm.resultType = 1;
  ruleForm.factor = '';
  ruleForm.itemNo = itemNo;
  ruleForm.rptGroup = rptGroup;
  ruleForm.isEnable = 1;
  ruleForm.exceptionSymbol = 'M';
}
/**行选中点击事件 */
function specialRuleRowClick({ row }) {
  Object.assign(ruleForm, row);
  specialRuleTabRef.value?.setCurrentRow(row);
}
/**删除特殊规则 */
async function deleteSpecialRule() {
  const row = specialRuleTabRef.value?.getCurrentRecord();
  if (IsEmpty(row.id)) {
    VxeMessage('请选中要删除的项', VxeNotifyType.error);
    return;
  }
  const type = await VXETable.modal.confirm('确定删除选中记录?');
  if (type === 'confirm') {
    proxy.$http
      .post('/lab/itemDictSpecialRules/deleteItemDictSpecialRules', { ids: [row.id] })
      .then((res: any) => {
        findSpecialRules();
      })
      .catch((err: any) => {
        VxeMessage('修改异常', VxeNotifyType.error);
      });
  }
}
/**保存特殊规则 */
function saveSpecialRule() {
  if (IsEmpty(ruleForm.itemNo)) {
    ruleForm.itemNo = itemNo;
  }
  if (IsEmpty(ruleForm.rptGroup)) {
    ruleForm.rptGroup = rptGroup;
  }
  let url = '/lab/itemDictSpecialRules/addItemDictSpecialRules';
  if (!IsEmpty(ruleForm.id)) {
    url = '/lab/itemDictSpecialRules/editItemDictSpecialRules';
  }
  proxy.$http
    .post(url, ruleForm)
    .then((res: any) => {
      findSpecialRules();
    })
    .catch((err: any) => {
      VxeMessage('修改异常', VxeNotifyType.error);
    });
}
/**结果值公式例句 */
function resulthandle() {
  if (ruleForm.resultType === 1) {
    ruleForm.factor = `testresult > 5`;
  }
  else if (ruleForm.resultType === 2) {
    ruleForm.factor = `testresult > 5.0`;
  }
  else if (ruleForm.resultType === 3) {
    ruleForm.factor = `'testresult' = '值'`;
  } else {
    ruleForm.factor = ``;
  }
}

/**OD值公式例句 */
function odhandle() {
  if (ruleForm.resultType === 1) {
    ruleForm.factor = `od > 5`;
  }
  else if (ruleForm.resultType === 2) {
    ruleForm.factor = `od > 5.0`;
  }
  else if (ruleForm.resultType === 3) {
    ruleForm.factor = `'od' = '值'`;
  } else {
    ruleForm.factor = ``;
  }
}

/**CUTOFF值公式例句 */
function cutoffhandle() {
  if (ruleForm.resultType === 1) {
    ruleForm.factor = `cutoff > 5`;
  }
  else if (ruleForm.resultType === 2) {
    ruleForm.factor = `cutoff > 5.0`;
  }
  else if (ruleForm.resultType === 3) {
    ruleForm.factor = `'cutoff' = '值'`;
  } else {
    ruleForm.factor = ``;
  }
}
/**结果标志选择改变 */
function dropSelectConfirm(e) {
  e.aimKeys.forEach((item) => {
    ruleForm[item.targetField] = e.row[item.sourceField];
  });
}
/**结果标记 */
function calcResultFlagText(row) {
  if (dictResultFlagList.length <= 0) {
    setTimeout(() => {
      calcResultFlagText(row);
      return;
    }, 50);
  }
  let a = '';
  const arr = dictResultFlagList.filter(p => p.code === row.exceptionSymbol);
  if (arr && arr.length > 0) {
    a = arr[0].name;
  }
  return a;
}
</script>
<style lang="scss" scoped>
#labreportitemRefer {
  width: 100%;
  height: 100%;

  .horizontalLine {
    :deep(.splitpanes__splitter) {
      background-color: $base-white;
    }
  }

  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }

  .tableBody {
    height: calc(100% - 40px);
  }
}
</style>
